import tkinter as tk
from PIL import Image, ImageTk
from tkinter import ttk
from tkinter import messagebox
from datetime import datetime
from Logic.button_history_check import button_history_check
from UI.balance import balance
from UI.Purchase_page import purchase
from Logic.valid_number_check import is_valid_number


def main():
    '''Create the main window window1
    and disable the ability to change
    the window size
    '''
    window1 = tk.Tk()
    window1.title("Non-Resizable Window with Scrollable Images")


    window1.resizable(False, False) # 禁止改变窗口大小
    window1.geometry("960x800")




    def show_product_info(name, price, image_path):


        window2 = tk.Toplevel(window1)  # Use Toplevel to ensure that window2 is a sub window of window1
        window2.resizable(False, False)
        window2.geometry('500x500')
        label1 = ttk.Label(window2, text="Please complete your bill.")
        label1.place(x=170, y=0)
        label2 = ttk.Label(window2, text="Quantity     : ")
        label2.place(x=90, y=150)
        entry_number = ttk.Entry(window2)
        entry_number.place(x=180, y=150)
        label3 = ttk.Label(window2, text="Description : ")
        label3.place(x=90, y=200)
        entry_description = ttk.Entry(window2)
        entry_description.place(x=180, y=200)
        label4 = ttk.Label(window2, text=f"The name of this product : {name}")
        label4.place(x=90, y=50)
        label5 = ttk.Label(window2, text=f"The price of this product : {price}")
        label5.place(x=90, y=100)


        # Create a function to make payment after clicking the 'pay' button
        def button_pay_check():

            try:
                #Obtain the quantity of inputs
                quantity_str = entry_number.get()
                description_str = entry_description.get()
                #Check if the quantity is a valid integer
                if not is_valid_number(quantity_str):
                    raise ValueError("Please enter a valid integer！")

                quantity = int(quantity_str)

                # Get product prices
                product_price = float(price.replace("¥", ""))  #Remove currency symbol


                with open("balance.txt", "r") as f:
                    money = f.read().strip()




                new_money = float(money) - product_price * quantity

                # Check if the balance is sufficient
                if new_money < 0:
                    raise ValueError("Insufficient balance, please recharge and try again！")

                # Write a new balance
                with open("balance.txt", "w") as f:
                    f.write(str(new_money))

                # write the history

                with open("history.txt", "a",encoding="utf-8") as f:
                    now = datetime.now()
                    f.write(f"{now} ：Purchased {quantity} of {name}.{description_str}\n")


                messagebox.showinfo("Purchase Successfully", "Thanks for purchasing ！")

            except ValueError as trouble:
                messagebox.showwarning("Tip", str(trouble))  # Display specific errors


        button_pay = ttk.Button(window2, text="Pay", command=button_pay_check)
        button_pay.place(x=200, y=400)

    # Create a top title box and add content
    top_frame = tk.Frame(window1, bg='white')
    top_frame.pack(fill=tk.X)  # Expand the width of the framework to the entire window


    title_label = tk.Label(top_frame, text="Welcome to Purchase App ! Check anything you want !", font=("Helvetica", 20),
                           bg='white')
    title_label.pack(pady=10)

    # Create a framework that accommodates scrollbars and canvases
    frame = tk.Frame(window1, bg='white')
    frame.pack(fill=tk.BOTH, expand=True)  # Extend the framework to the entire window and allow for resizing

    # Create a canvas
    canvas = tk.Canvas(frame, bg='white')
    canvas.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)

    # Create a vertical scrollbar and associate it with the canvas

    vscrollbar = tk.Scrollbar(frame, orient=tk.VERTICAL, command=canvas.yview)
    # Specify the scrollbar as vertical scrolling and associate it with the canvas
    # Configure the canvas to affect the scrollbar, set:Ensure that both roll together
    canvas.configure(yscrollcommand=vscrollbar.set)

    # create an inner_frame to contain pictures
    inner_frame = tk.Frame(canvas, bg='white')
    # put inner_frame in the canvas as a window
    canvas.create_window((0, 0), window=inner_frame, anchor='nw')
    '''
    Create two functions to implement the special effect of 
    changing the color of an image when the mouse is moved over it
    '''
    def on_enter(event):
        event.widget.config(bg='#e0e0e0')  # Move the mouse to the color of the image(lightgrey)

    def on_leave(event):
        event.widget.config(bg='white')  # Mouse leaves color

    # Set up a dictionary to store all products, including image paths, prices, and product names
    product_info = {
        "Lays.jpg": ("Lays", "¥5.00"),
        "Nong_fu _spring_water.jpg": ("Nongfu Spring Water", "¥2.00"),
        "Choclairs.jpg": ("Choclairs", "¥3.00"),
        "wei_long.jpg": ("Weilong", "¥4.00"),
        "cola.jpg": ("Cola", "¥3.00"),
        "Master_kang.jpg": ("Master Kang", "¥3.00"),
        "Sprite.jpg": ("Sprite", "¥3.00"),
        "Oreo.jpg": ("Oreo", "¥6.00"),
        "iced_tea.jpg": ("Iced Black Tea", "¥4.00")
    }

    # Using a list to reference the image path of a product list
    image_paths = list(product_info.keys())

    # Use enumerate to traverse the list, where i is the index value and path is the path of the image
    for i, path in enumerate(image_paths):
        img = Image.open(path)
        new_size = (270, 270)
        img = img.resize(new_size)
        photo = ImageTk.PhotoImage(img)


        # Create button and add image
        button = tk.Button(inner_frame, image=photo,
                           command=lambda p=path: show_product_info(
                               product_info[p][0],
                               product_info[p][1],
                               p),
                           bg='white', bd=0, relief=tk.FLAT)  # Set the background color to white, borderless, and flat style
        button.image = photo  # Maintain reference to images
        # Three images per line, where i is the index of each image and specifies the spacing between the images
        button.grid(row=i // 3, column=i % 3, padx=20, pady=20)

        # Use bind to bind events and corresponding functions for moving the mouse in and out of images
        button.bind("<Enter>", on_enter)
        button.bind("<Leave>", on_leave)

    # Update the scrolling area of the canvas
    def update(event):
        canvas.config(scrollregion=canvas.bbox('all'))

    # Bind configuration events to update scrolling areas
    canvas.bind('<Configure>', update)
    '''Ensure that whenever the configuration of Canvas changes , 
    the scrolling area of Canvas is recalculated and updated 
    so that users can view the entire content of Canvas through the scrollbar
    This ensures that users only scroll to view the pictures on the canvas instead of the blank space
    '''
    # Binding Mouse Wheel Event
    def on_mouse_wheel(event):
        canvas.yview_scroll(int(-1 * (event.delta / 120)), "units")

    canvas.bind_all("<MouseWheel>", on_mouse_wheel)



    # Create a bottom frame to place buttons
    bottom_frame = tk.Frame(window1, bg='white')
    bottom_frame.pack(fill=tk.X, side=tk.BOTTOM, pady=10)

    # Add three buttons
    button1 = ttk.Button(bottom_frame, text="Quick Purchase",command=purchase)
    button2 = ttk.Button(bottom_frame, text="History",command=button_history_check)
    button3 = ttk.Button(bottom_frame, text="Balance",command=balance)

    # Arrange buttons in a row using a grid layout

    button1.grid(row=0, column=0, sticky='W', padx=(100, 0))
    button2.grid(row=0, column=1, sticky='EW')
    button3.grid(row=0, column=2, sticky='E', padx=(0, 100))

    # Set column weights to center the middle button
    bottom_frame.grid_columnconfigure(0, weight=1)  # 左边的列有一定的伸缩性
    bottom_frame.grid_columnconfigure(1, weight=0)  # 中间的列不伸缩，保持固定大小
    bottom_frame.grid_columnconfigure(2, weight=1)  # 右边的列有一定的伸缩性

    window1.mainloop()

if __name__ == "__main__":
    main()